package com.zb.service.imp.base;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.zb.dao.base.OmsCommonDao;
import com.zb.dao.ext.charger.OmsChargerDao;
import com.zb.dao.ext.common.OmsSplitratioSchemeDao;
import com.zb.dao.ext.system.OmsServiceSplitRatioRepo;
import com.zb.entity.base.*;
import com.zb.entity.charger.OmsCharger;
import com.zb.entity.exception.OmsDaoException;
import com.zb.service.base.ServiceSplitratioService;
import com.zb.util.StringUtil;
import com.zb.util.OmsConstant.MsgCodeEnum;

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class ServiceSplitratioServiceImpl extends BaseService implements ServiceSplitratioService{

	private Log log = LogFactory.getLog(ServiceSplitratioServiceImpl.class);

	@Autowired
	@Qualifier("base")
	private OmsCommonDao<OmsServiceSplitratio> serviceSplitratioDaoImpl;
	@Autowired
	private OmsSplitratioSchemeDao splitratioSchemeDaoImpl;
	@Autowired
	private RedisTemplate<String, String> redisTempalate;
	@Resource
	OmsChargerDao omsChargerDao;
	@Resource
	OmsServiceSplitRatioRepo omsServiceSplitRatioRepo;

	@Override
	public  JsonCommon<?> add(String[] entityTypes,String[] entityIds,String[] entityNames ,String serviceNo,
			String[] ratios,String[] minAmount,String schemeName,String create_oper_id )
	{
		try
		{
//			if(entityTypes != null && entityIds != null &&
//					ratios != null && minAmount != null && chargeIds != null &&
//					entityTypes.length == entityIds.length &&
//					entityTypes.length == ratios.length &&
//					entityTypes.length == minAmount.length)
//			{
//				Integer splitratioNo = this.findMaxSplitratioNo();
//				Date now = new Date();
//				boolean insertTypeKo= false;
//				for (int i = 0;i <entityTypes.length;i++)
//				{
//					if (StringUtils.isNumeric(entityTypes[i]))
//					{
//						OmsSplitratioScheme splitratioScheme = new OmsSplitratioScheme();
//						splitratioScheme.setScheme_name(schemeName);
//						splitratioScheme.setEntity_id(entityIds[i]);
//						splitratioScheme.setEntity_type(Integer.parseInt(entityTypes[i]));
//						splitratioScheme.setRatios(ratios[i]);
//						splitratioScheme.setMin_amount(minAmount[i]);
//						splitratioScheme.setScheme_no(splitratioNo);
//						splitratioScheme.setValid_flag(1);
//						splitratioScheme.setCreate_time(now);
//						splitratioScheme.setUpdate_time(now);
////						schemes.add(splitratioScheme);
//						splitratioSchemeDaoImpl.add(splitratioScheme);
//						insertTypeKo = true;
//					}
//				}
//				
//				if (insertTypeKo)
//				{
//					for (String chargeId : chargeIds)
//					{
//						OmsServiceSplitratio splitratio = new OmsServiceSplitratio();
//						splitratio.setCharger_id(chargeId);
//						splitratio.setService_no(serviceNo);
//						splitratio.setValid_flag(1);
//						splitratio.setScheme_no(Integer.toString(splitratioNo));
//						splitratio.setStation_id("");
//						serviceSplitratioDaoImpl.add(splitratio);
//					}
//				}
//			}
			
		//分成方案名称不能重复
	    OmsSplitratioScheme splitratioSchemeTmp = new OmsSplitratioScheme();
	    splitratioSchemeTmp.setScheme_name(schemeName);
		OmsSplitratioScheme splitratioSchemeQury = splitratioSchemeDaoImpl.findOneExample(splitratioSchemeTmp, null, null);
		if (splitratioSchemeQury != null) {
			JsonCommon  jfl = new JsonCommon();
			jfl.setCode(MsgCodeEnum.ERROR400.getMsgCode());
			jfl.setMsg(MsgCodeEnum.ERROR400.getMsgInfo()+":分成方案名称不能重复");
			return jfl;
		}
			
		if(entityTypes != null && entityIds != null &&
			ratios != null && minAmount != null && entityNames != null &&
			entityTypes.length == entityIds.length &&
			entityTypes.length == entityNames.length &&
			entityTypes.length == ratios.length &&
			entityTypes.length == minAmount.length)
			{
				Integer splitratioNo = this.findMaxSplitratioNo();
				Date now = new Date();
				for (int i = 0;i <entityTypes.length;i++)
				{
					if (StringUtils.isNumeric(entityTypes[i]))
					{
						OmsSplitratioScheme splitratioScheme = new OmsSplitratioScheme();
						splitratioScheme.setScheme_name(schemeName);
						splitratioScheme.setEntity_id(entityIds[i]);
						splitratioScheme.setEntity_name(entityNames[i]);
						splitratioScheme.setEntity_type(Integer.parseInt(entityTypes[i]));
						splitratioScheme.setRatios(ratios[i]);
						splitratioScheme.setMin_amount(minAmount[i]);
						splitratioScheme.setScheme_no(splitratioNo);
						splitratioScheme.setService_no(serviceNo);
						splitratioScheme.setValid_flag(1);
						splitratioScheme.setCreate_time(now);
						splitratioScheme.setUpdate_time(now);
						splitratioScheme.setCreate_oper_id(create_oper_id);
	//					schemes.add(splitratioScheme);
						splitratioSchemeDaoImpl.add(splitratioScheme);
					}
				}
			}
		}
		catch(Exception e)
		{
			this.logError(e.getMessage(), e);
			return this.buildError400JsonCommon();
		}
		
		return this.buildSuccessJsonCommon("ok");
	}

	@Override
	public JsonCommon<?> update(String[] entityTypes,String[] entityIds,String[] entityNames ,
			String[] ratios,String[] minAmount,String serviceNo, String schemeName,String schemeNo,Integer valid_flag,String update_oper_id )
	{
		try 
		{
//			if(StringUtils.isNumeric(schemeNo) && 
//					entityTypes != null && entityIds != null &&
//					ratios != null && minAmount != null && chargeIds != null &&
//					entityTypes.length == entityIds.length &&
//					entityTypes.length == ratios.length &&
//					entityTypes.length == minAmount.length)
//			{
//				//先删除
//				splitratioSchemeDaoImpl.deleteShemeByShemeNo(schemeNo);
//				splitratioSchemeDaoImpl.deleteSplitratioByShemeNo(schemeNo);
//				//
//				Integer splitratioNo = Integer.parseInt(schemeNo);
//				Date now = new Date();
//				boolean insertTypeKo= false;
//				for (int i = 0;i <entityTypes.length;i++)
//				{
//					if (StringUtils.isNumeric(entityTypes[i]))
//					{
//						OmsSplitratioScheme splitratioScheme = new OmsSplitratioScheme();
//						splitratioScheme.setScheme_name(schemeName);
//						splitratioScheme.setEntity_id(entityIds[i]);
//						splitratioScheme.setEntity_type(Integer.parseInt(entityTypes[i]));
//						splitratioScheme.setRatios(ratios[i]);
//						splitratioScheme.setMin_amount(minAmount[i]);
//						splitratioScheme.setScheme_no(splitratioNo);
//						splitratioScheme.setValid_flag(1);
//						splitratioScheme.setCreate_time(now);
//						splitratioScheme.setUpdate_time(now);
//						splitratioSchemeDaoImpl.add(splitratioScheme);
//						insertTypeKo = true;
//					}
//				}
//				
//				if (insertTypeKo)
//				{
//					for (String chargeId : chargeIds)
//					{
//						OmsServiceSplitratio splitratio = new OmsServiceSplitratio();
//						splitratio.setCharger_id(chargeId);
//						splitratio.setService_no(serviceNo);
//						splitratio.setScheme_no(Integer.toString(splitratioNo));
//						splitratio.setStation_id("");
//						splitratio.setValid_flag(1);
//						serviceSplitratioDaoImpl.add(splitratio);
//					}
//				}
//			}
			//分成方案名称不能重复
		    OmsSplitratioScheme splitratioSchemeTmp = new OmsSplitratioScheme();
		    String condition = " where scheme_no <>" + schemeNo + " and scheme_name = '" + schemeName + "'";
		    List<OmsSplitratioScheme> listOmsSplitratioScheme = splitratioSchemeDaoImpl.findListByCondition(splitratioSchemeTmp, condition);
			if (listOmsSplitratioScheme.size() >0 ) {
				JsonCommon  jfl = new JsonCommon();
				jfl.setCode(MsgCodeEnum.ERROR400.getMsgCode());
				jfl.setMsg(MsgCodeEnum.ERROR400.getMsgInfo()+":分成方案名称不能重复");
				return jfl;
			}
			
			if(entityTypes != null && entityIds != null &&
					ratios != null && minAmount != null && entityNames != null &&
					entityTypes.length == entityIds.length &&
					entityTypes.length == entityNames.length &&
					entityTypes.length == ratios.length &&
					entityTypes.length == minAmount.length)
				{
				//先删除
				splitratioSchemeDaoImpl.deleteShemeByShemeNo(schemeNo);
				//splitratioSchemeDaoImpl.deleteSplitratioByShemeNo(schemeNo);   //更新分成方案，不需要删除该方案关联电桩信息
				//
				Integer splitratioNo = Integer.parseInt(schemeNo);
				Date now = new Date();
				for (int i = 0;i <entityTypes.length;i++)
				{
					if (StringUtils.isNumeric(entityTypes[i]))
					{
						OmsSplitratioScheme splitratioScheme = new OmsSplitratioScheme();
						splitratioScheme.setScheme_name(schemeName);
						splitratioScheme.setEntity_id(entityIds[i]);
						splitratioScheme.setEntity_name(entityNames[i]);
						splitratioScheme.setEntity_type(Integer.parseInt(entityTypes[i]));
						splitratioScheme.setRatios(ratios[i]);
						splitratioScheme.setMin_amount(minAmount[i]);
						splitratioScheme.setScheme_no(splitratioNo);
						splitratioScheme.setValid_flag(valid_flag);
						splitratioScheme.setCreate_time(now);
						splitratioScheme.setUpdate_time(now);
						splitratioScheme.setService_no(serviceNo);
						splitratioScheme.setUpdate_oper_id(update_oper_id);
						splitratioSchemeDaoImpl.add(splitratioScheme);
					}
				}
			}
			
			return this.buildSuccessJsonCommon("ok");
		} 
		catch (OmsDaoException e) 
		{
			this.logError(e.getMessage(), e);
			return this.buildError400JsonCommon();
		}
	}

	@Override
	public void bindChargeIds(String serviceNo,String[] chargeIds,String schemeNo )
	{
		try 
		{
			List<OmsServiceSplitRatioEntity> list = new ArrayList<>();
			for (String chargeId : chargeIds)
			{
				OmsServiceSplitRatioEntity vo = omsServiceSplitRatioRepo.findByChargerIdAndServiceNo(chargeId, serviceNo);

				if(vo == null)
				{
					vo = new OmsServiceSplitRatioEntity();
					vo.setServiceNo(serviceNo);
					vo.setChargerId(chargeId);
					vo.setValidFlag(1);
				}
				vo.setSchemeNo(Integer.valueOf(schemeNo));
				list.add(vo);
			}
			if(!list.isEmpty())
				omsServiceSplitRatioRepo.save(list);
		} 
		catch (Exception e)
		{
			log.error(e.getMessage(), e);
			throw e;
		}
	}
	
	@Override
	public JsonCommon<?> delete(String schemeNo) {
		try 
		{
			splitratioSchemeDaoImpl.logicDelShemeByShemeNo(schemeNo);
			splitratioSchemeDaoImpl.logicDelSplitratioBySchemeNo(schemeNo);
			return this.buildSuccessJsonCommon("success");
		} catch (OmsDaoException e) {
			this.logError(e.getMessage(), e);
			return this.buildError400JsonCommon();
		}
	}

	@Override
	public JsonForList<?> findPageObjs(OmsCommonParam param) 
	{
		try 
		{
			List<OmsSplitratioScheme> lst = splitratioSchemeDaoImpl.findSchemesByPage(param);
			int total = 0;
			if (param.isQueryTotal())
			{
				total = splitratioSchemeDaoImpl.findCountSchemes();
			}
			return this.buildSuccessJsonForList(param, lst, total);
		} 
		catch (Exception e) 
		{
			this.logError(e.getMessage(), e);
			return this.buildError400JsonForList();
		}
	}
	
	private Integer findMaxSplitratioNo()throws OmsDaoException
	{
		Integer splitratioNo = null;
		try
		{
			String key = "idSequence:splitratioSchemeId";
			ValueOperations<String, String> ops = redisTempalate.opsForValue();
			String value = ops.get(key);
			if (StringUtils.isNumeric(value))
			{
				splitratioNo = Integer.parseInt(value);
			}
			else
			{
				splitratioNo = splitratioSchemeDaoImpl.findMaxSplitratioNo();
				ops.set(key, splitratioNo.toString());
			}
			ops.increment(key, 1l);
		}
		catch(Exception e)
		{
			if (e.getMessage().contains("JedisDataException"))
			{
				splitratioNo = splitratioSchemeDaoImpl.findMaxSplitratioNo();
			}
			else
			{
				throw new OmsDaoException(e);
			}
		}
		
		
		return splitratioNo+1;
	}

	@Override
	public JsonCommon<?> findSchemeBySchemeNo(String schemeNo) 
	{
		try 
		{
			Map<String, Object> result = splitratioSchemeDaoImpl.findSchemeBySchemeNo(schemeNo);
			if (result != null)
			{
				result.put("entitys", splitratioSchemeDaoImpl.findSchemeDetailsEntitys(schemeNo));
				return this.buildSuccessJsonCommon(result);
			}
			else
			{
				return this.buildOtherJsonCommon(MsgCodeEnum.ERROR400.getMsgCode(), "the scheme no is not exists!");
			}
		} 
		catch (OmsDaoException e) 
		{
			this.logError(e.getMessage(), e);
			return this.buildError400JsonCommon();
		}
	}

	@Override
	public JsonForList<?> findChargerBySchemeNo(String schemeNo,String serviceNo, String cityCode, String likeValue) {
		try 
		{
			List<OmsChargerShow> lst = splitratioSchemeDaoImpl.findChargersBySchemeNo(schemeNo, serviceNo, cityCode, likeValue, null);
			return this.buildSuccessJsonForList(lst);
		} 
		catch (Exception e) 
		{
			this.logError(e.getMessage(), e);
			return this.buildError400JsonForList();
		}
	}

	@Override
	public JsonForList<?> getUnbindCharges(String serviceNo, String schemeNo) {
		StringBuilder condition = new StringBuilder( "where charger_id not in (select charger_id from oms_service_splitratio where 1=1");
		//serviceNo不能为空
		if(StringUtil.isNumeric(serviceNo)){
			condition.append(" and service_no ='"+serviceNo +"'");
		}
		condition.append(") and valid_flag = 1 ");
		//查找此分成方案
		//如果此方案是通配，则查找所有符合条件的桩；如果此方案不是通配，则查找分成方案的运营商和合作商作为条件查找桩
		try {
			List<OmsSplitratioScheme> listSplitratio = splitratioSchemeDaoImpl.findSchemeDetailsEntitys(schemeNo);
			if (listSplitratio.size()>0 && !"*".equals(listSplitratio.get(0).getEntity_id())) {
				StringBuffer operMerchantId = new StringBuffer("");    //运营商
				StringBuffer merchantId = new StringBuffer("");       //合作商
				for(OmsSplitratioScheme omsSplitratioScheme:listSplitratio){
					if (omsSplitratioScheme.getEntity_type()==1) {
						operMerchantId = operMerchantId.append("'" + omsSplitratioScheme.getEntity_id() + "',");
					}else if (omsSplitratioScheme.getEntity_type()==4) {
						merchantId = merchantId.append("'" + omsSplitratioScheme.getEntity_id() + "',");
					}
				}
				if (operMerchantId.length()>0) {
					operMerchantId.deleteCharAt(operMerchantId.length()-1);
				}
				if (merchantId.length()>0) {
					merchantId.deleteCharAt(merchantId.length()-1);
				}
				
				//查询只有运营商，没有合作商的桩
				StringBuilder condition1 = new StringBuilder( " and (entity_id is null or trim(entity_id)='') ");
				//查询既有运营商，也有有合作商的桩
				StringBuilder condition2 = new StringBuilder( " and entity_id is not null and trim(entity_id)!='' ");
				if (operMerchantId.length()>0) {
					condition1.append(" and oper_merchant_id in (" + operMerchantId + ")");
					condition2.append(" and oper_merchant_id in (" + operMerchantId + ")");
				}
				List<OmsCharger> list1 = omsChargerDao.findListByCondition(new OmsCharger(), condition.toString()+condition1.toString());
				
				if (merchantId.length()>0) {
					condition2.append(" and entity_id in (" + merchantId +")" );
				}
				
				List<OmsCharger> list2 = omsChargerDao.findListByCondition(new OmsCharger(), condition.toString()+condition2.toString());
				
				list1.addAll(list2);
				return new JsonForList<>(list1, "200", "ok");
			}
				
		} catch (OmsDaoException e) {
			e.printStackTrace();
		}
		
		List<OmsCharger> list = omsChargerDao.findListByCondition(new OmsCharger(), condition.toString());
		return new JsonForList<>(list, "200", "ok");
	}

	@Override
	public JsonForList<?> unBind(List<String> chargerIdList, String serviceNo, String schemeNo) {
		try {
			StringBuilder sb = new StringBuilder("delete from oms_service_splitratio  where 1=1 "); 
			if(StringUtil.isNotBlank(serviceNo)){
				sb.append(" and service_no = '"+serviceNo+"'" );
			}
			if(StringUtil.isNumeric(schemeNo)){
				sb.append(" and scheme_no = "+schemeNo);
			}
			sb.append(" and charger_id in (");
			for(String chargerId:chargerIdList){
				sb.append("'"+chargerId+"',");
			}
			sb.deleteCharAt(sb.length()-1);
			sb.append(")");
			splitratioSchemeDaoImpl.exec(sb.toString());
			return new JsonForList<>(null, "200", " delete ok");
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonForList<>(null, "103011", e.getMessage());
		}
	}

	@Override
	public JsonForList<OmsSplitratioScheme> findSchemeByChargerId(String chargerId) {
		try 
		{			
			OmsCharger omsCharger = omsChargerDao.findOneExampleByCondition(new OmsCharger(), " where charger_id = '"+chargerId+"'");
			
			List<OmsSplitratioScheme> lst = splitratioSchemeDaoImpl.findSchemeByChargerId(omsCharger);
			
			JsonForList<OmsSplitratioScheme> jfl = new JsonForList<OmsSplitratioScheme>();
			
			jfl.setList(lst);
			jfl.setCode(MsgCodeEnum.SUCCESS.getMsgCode());
			jfl.setMsg(MsgCodeEnum.SUCCESS.getMsgInfo());
			return jfl;
		} 
		catch (Exception e) 
		{
			this.logError(e.getMessage(), e);
			return this.buildError400JsonForList();
		}
	}

}
